package com.xiaomei.manager.service.impl;

import java.util.Collections;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xiaomei.manager.dao.SysUserMapper;
import com.xiaomei.manager.model.SysUser;
import com.xiaomei.manager.service.IRoleService;
import com.xiaomei.manager.service.ISysUserService;

@Service
public class SysUserServiceImpl implements ISysUserService{
	/**
     * 创建用户
     * @param user
     */
	@Autowired
	private SysUserMapper SysUMapper;
	@Autowired
	private PasswordHelper passwordHelper;
	@Autowired
    private IRoleService roleService;
	
    public SysUser createUser(SysUser user){
    	passwordHelper.encryptPassword(user);
    	if(SysUMapper.insert(user) > 0){
    		user.setId(SysUMapper.selectLastInsertID());		
    		return user;
    	}else{
    		return null;
    	}
    }

    public SysUser updateUser(SysUser user){
    	if(SysUMapper.updateByPrimaryKey(user) > 0){
    		return user;
    	}else{
    		return null;
    	}
    }

    public void deleteUser(Long userId){
    	if(SysUMapper.deleteByPrimaryKey(userId) > 0){
    		
    	}   
    }

    /**
     * 修改密码
     * @param userId
     * @param newPassword
     */
    public void changePassword(Long userId, String newPassword){
    	 SysUser user = findOne(userId);
         user.setPassword(newPassword);
         passwordHelper.encryptPassword(user);
         updateUser(user);
    }


    public SysUser findOne(Long userId){
    	return SysUMapper.selectByPrimaryKey(userId);
    }

    public List<SysUser> findAll(){
    	return SysUMapper.selectAll();
    }

    /**
     * 根据用户名查找用户
     * @param username
     * @return
     */
    public SysUser findByUsername(String username){
    	return SysUMapper.selectByUsername(username);
    }

    /**
     * 根据用户名查找其角色
     * @param username
     * @return
     */
    public Set<String> findRoles(String username){
    	   SysUser user =findByUsername(username);
           if(user == null) {
               return Collections.EMPTY_SET;
           }
           return roleService.findRoles(user.getRoleIdLst().toArray(new Long[0]));
    }

    /**
     * 根据用户名查找其权限
     * @param username
     * @return
     */
    public Set<String> findPermissions(String username){
    	  SysUser user =findByUsername(username);
          if(user == null) {
              return Collections.EMPTY_SET;
          }
          return roleService.findPermissions(user.getRoleIdLst().toArray(new Long[0]));
      }
 
}
